﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;

namespace Xceed.Silverlight.Data.Stats
{
  public class GeometricMeanFunction : CumulativeStatFunction
  {
    public GeometricMeanFunction()
      : base()
    {
    }

    public GeometricMeanFunction( string resultPropertyName, string sourcePropertyName )
      : base( resultPropertyName, sourcePropertyName )
    {
    }

    #region PrerequisiteFunctions Property

    protected internal override StatFunction[] PrerequisiteFunctions
    {
      get
      {
        StatFunction[] prerequisites = m_prerequisites;

        if( prerequisites == null )
        {
          prerequisites = new StatFunction[]
          {
            new CountFunction( "GeometricMeanFunction.Count", this.SourcePropertyName )
          };

          if( this.IsSealed )
            m_prerequisites = prerequisites;
        }

        return prerequisites;
      }
    }

    #endregion PrerequisiteFunctions Property

    protected internal override void Validate()
    {
      base.Validate();
      base.ValidateSourcePropertyName( 1 );
    }

    protected override void Initialize( Type[] sourcePropertyTypes )
    {
      base.Initialize( sourcePropertyTypes );

      switch( Type.GetTypeCode( sourcePropertyTypes[ 0 ] ) )
      {
        case TypeCode.Char:
        case TypeCode.Byte:
        case TypeCode.SByte:
        case TypeCode.Int16:
        case TypeCode.Int32:
        case TypeCode.Int64:
        case TypeCode.UInt16:
        case TypeCode.UInt32:
        case TypeCode.UInt64:
          m_accumulationType = TypeCode.UInt64;
          break;

        case TypeCode.Single:
        case TypeCode.Double:
          m_accumulationType = TypeCode.Double;
          break;

        case TypeCode.Decimal:
          m_accumulationType = TypeCode.Decimal;
          break;
      }
    }

    protected internal override void InitializePrerequisites( StatResult[] prerequisitesValues )
    {
      if( prerequisitesValues.Length != 1 )
        throw new ArgumentException( "The prerequisite initializers do not match the PrerequisiteFunctions." );

      checked
      {
        m_count = Convert.ToInt64( prerequisitesValues[ 0 ].Value );

        if( m_count == 0 )
        {
          // No need to go further (i.e. Accumulate), the result cannot be calculated.
          throw new DivideByZeroException();
        }
      }
    }

    protected internal override void Reset()
    {
      m_ulongProduct = 1;
      m_doubleProduct = 1d;
      m_decimalProduct = 1m;
      m_count = 0;
    }

    protected internal override void Accumulate( object[] values )
    {
      if( StatFunction.CanProcessValues( values, 1 ) )
      {
        checked
        {
          switch( m_accumulationType )
          {
            case TypeCode.UInt64:
              {
                ulong number = Convert.ToUInt64( values[ 0 ] );

                if( number > 0 )
                {
                  m_ulongProduct *= number;
                }
                else
                {
                  throw new InvalidValueException( "The geometric mean can only be calculated on elements whose values are greater than zero." );
                }
              }
              break;

            case TypeCode.Double:
              {
                double number = Convert.ToDouble( values[ 0 ] );

                if( number > 0d )
                {
                  m_doubleProduct *= number;
                }
                else
                {
                  throw new InvalidValueException( "The geometric mean can only be calculated on elements whose values are greater than zero." );
                }
              }
              break;

            case TypeCode.Decimal:
              {
                decimal number = Convert.ToDecimal( values[ 0 ] );

                if( number > 0m )
                {
                  m_decimalProduct *= number;
                }
                else
                {
                  throw new InvalidValueException( "The geometric mean can only be calculated on elements whose values are greater than zero." );
                }
              }
              break;
          }
        }
      }
    }

    protected internal override void AccumulateChildResult( StatResult childResult )
    {
      GeometricMeanResult geoMeanResult = ( GeometricMeanResult )childResult;

      checked
      {
        switch( m_accumulationType )
        {
          case TypeCode.UInt64:
            m_ulongProduct *= Convert.ToUInt64( geoMeanResult.Product );
            break;

          case TypeCode.Double:
            m_doubleProduct *= Convert.ToDouble( geoMeanResult.Product );
            break;

          case TypeCode.Decimal:
            m_decimalProduct *= Convert.ToDecimal( geoMeanResult.Product );
            break;
        }
      }
    }

    protected internal override StatResult GetResult()
    {
      object result = null;
      object product = null;

      checked
      {
        switch( m_accumulationType )
        {
          case TypeCode.UInt64:
            product = m_ulongProduct;
            result = Math.Pow( Convert.ToDouble( m_ulongProduct ), 1d / m_count );
            break;

          case TypeCode.Double:
            product = m_doubleProduct;
            result = Math.Pow( m_doubleProduct, 1d / m_count );
            break;

          case TypeCode.Decimal:
            product = m_decimalProduct;
            result = Math.Pow( Convert.ToDouble( m_decimalProduct ), 1d / m_count );
            break;
        }
      }

      return new GeometricMeanResult( result, product );
    }

    private TypeCode m_accumulationType = TypeCode.Empty;
    private StatFunction[] m_prerequisites;
    private long m_count;
    private ulong m_ulongProduct;
    private double m_doubleProduct;
    private decimal m_decimalProduct;

    private class GeometricMeanResult : StatResult
    {
      public GeometricMeanResult( object value, object product )
        : base( value )
      {
        m_product = product;
      }

      #region Product property

      public object Product
      {
        get
        {
          return m_product;
        }
      }

      private object m_product;

      #endregion
    }
  }
}
